package com.zahb.qadx.ui.activity.videopage;


import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.CommonData;
import com.zahb.qadx.model.MicroVideoData;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 单标题微视频列表
 * LEB
 */
public class TitlevideoFragment extends BaseFragmentExt implements OnRefreshLoadMoreListener, OnItemClickListener {


    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private boolean mIsFirstLoad = true;// 是否第一次，处理懒加载
    private boolean mHasClickToNewPage = false;// 记录点击跳转新页面
    private int mPage;
    private TaskAdapter mTaskAdapter;
    private MicroVideoData.MicroVideoBean microVideoBean;
    private int categoryId; //分类id

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;
    private CommonData<MicroVideoData.MicroVideoBean> microVideoBeans;
    public TitlevideoFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        categoryId=mArguments.getInt("categoryId");

    }

    private void updateTheNumberOfPlays() {
        Log.e("isshik",microVideoBean.getId()+"");
        addDisposable(RetrofitService.getNetService()
                .getPlayTheRefresh(microVideoBean.getId())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstLoad) {
            mIsFirstLoad = false;
            //refreshLayout.autoRefresh();
            onRefresh(refreshLayout);
            showSkeleton();
        }

        if (mHasClickToNewPage) {
            mHasClickToNewPage = false;
            refreshLayout.autoRefresh();
        }
    }
    public static TitlevideoFragment newInstance(int type,int categoryId) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        args.putInt("categoryId", categoryId);
        TitlevideoFragment fragment = new TitlevideoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_titlevideo;
    }

    @Override
    protected void initViews(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mTaskAdapter = new TitlevideoFragment.TaskAdapter(R.layout.item_list_video);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mTaskAdapter.setEmptyView(emptyView);
        mTaskAdapter.setUseEmpty(true);
        recyclerView.setAdapter(mTaskAdapter);
        mTaskAdapter.setOnItemClickListener(this);
        int divider = DisplayUtil.dip2px(10f);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                outRect.set(0, 0, 0, divider);
            }
        });

    }

    private void showSkeleton() {
        refreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(recyclerView)
                .adapter(mTaskAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(5)
                .load(R.layout.item_list_video_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                refreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    private void getTaskList() {
        Map<String, Object> params = new HashMap<>();
        params.put("categoryId",categoryId );
        params.put("pageNum",mPage );
        params.put("pageSize",10 );
        Gson mGson = new Gson();
        String json = mGson.toJson(params);
        Log.e("json",json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getStudentsGetAListOfMicroVideos(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore(1000);
                    if (response.getStatusCode() == 200) {
                        if (response.getData() != null) {
                            if (mPage == 1) {
                                mTaskAdapter.setList(response.getData().getList());
                                microVideoBeans = response.getData();
                            } else {
                                mTaskAdapter.addData(response.getData().getList());
                                microVideoBeans.getList().addAll(response.getData().getList());
                            }
                        }else {
                            showBindToast("已经到底了");
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.finishRefresh();
                    Tips.RequestError(getActivity());
                    refreshLayout.finishLoadMore(1000);
                    hideSkeleton();
                }));

    }
    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//
//        MicroVideoPlaybackActivity.actionStart(getContext(), mTaskAdapter.getItem(position), MicroVideoPlaybackActivity.TYPE_VIDEO);
//       getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
////       滑动
        microVideoBean=mTaskAdapter.getItem(position);
        Intent intent = new Intent(getActivity(), FlipVideoActivity.class);
        intent.putExtra("bean", microVideoBeans);
        intent.putExtra("value", position);
        intent.putExtra("categoryId", categoryId);
        intent.putExtra("mPage", mPage);
        intent.putExtra("mTaskAdapter", mTaskAdapter.getItem(position));
        startActivity(intent);
        getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        //更新微视频播放量
        updateTheNumberOfPlays();

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getTaskList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getTaskList();
    }

    private static class TaskAdapter extends BaseQuickAdapter<MicroVideoData.MicroVideoBean, BaseViewHolder> {

        TaskAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, MicroVideoData.MicroVideoBean task) {


            ImageLoaderKt.loadImageSameCorners(baseViewHolder.getView(R.id.video_chart),
                     task.getCoverImage(), 5f);
            baseViewHolder.setText(R.id.tv_sub_title, task.getName());
            baseViewHolder.setText(R.id.playVolume, task.getPlayVolume_Str() );
                baseViewHolder.setText(R.id.duration, "视频时长："+millisecondsToMinuteSecondStr(task.getDuration()));

        }
        // 将毫秒转为分钟：秒
        private static String millisecondsToMinuteSecondStr(int ms) {

            int seconds = (int) ms;
            String result = "";
            int min, second;
            min = seconds / 60;
            second = seconds - min * 60;

            if (min < 10) {
                result += "0" + min + ":";
            } else {
                result += min + ":";
            }
            if (second < 10) {
                result += "0" + second;
            } else {
                result += second;
            }
            return result;
        }
    }

}
